const defaultOptions = {
  top: 0,
  pid: "pid",
  id: "id"
};

class Li2tree {
  constructor(listData, options = defaultOptions) {
    this.listData = listData;
    this.top = options.top;
    this.pid = options.pid;
    this.id = options.id;
    this.level = 0;
    this.topList = listData.filter(item => {
      return item[this.pid] === this.top;
    });
  }

  convert(data = this.topList, level = 1) {
    data.forEach(item => {
      item.level = level;
      let children = this.listData.filter(i => {
        return i[this.pid] === item[this.id];
      });
      if (children.length === 0) {
        item.hasChild = false;
      } else {
        item.children = children;
        item.hasChild = true;
        this.convert(children, level + 1);
      }
    });
    return data;
  }
}

export default Li2tree;
